package com.example.test.model;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.openapi.legacy.AccountAPI;
import com.sina.weibo.sdk.openapi.legacy.CommentsAPI;
import com.sina.weibo.sdk.openapi.legacy.FriendshipsAPI;
import com.sina.weibo.sdk.openapi.legacy.SearchAPI;
import com.sina.weibo.sdk.openapi.legacy.StatusesAPI;
import com.sina.weibo.sdk.openapi.legacy.UsersAPI;
import com.sina.weibo.sdk.openapi.legacy.WeiboAPI.AUTHOR_FILTER;
import com.sina.weibo.sdk.openapi.legacy.WeiboAPI.COMMENTS_TYPE;
import com.sina.weibo.sdk.openapi.legacy.WeiboAPI.FEATURE;
import com.sina.weibo.sdk.openapi.legacy.WeiboAPI.SRC_FILTER;
import com.sina.weibo.sdk.openapi.legacy.WeiboAPI.TYPE_FILTER;
import com.tencent.weibo.sdk.android.model.GlobalVar;

import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class SinaAPI {
	//获取当前登录用户uid
	public static void getUserUid(final Handler handler)
	{
		if(!(GlobalVar.enWhich.equals("all")||GlobalVar.enWhich.equals("sina")))
			return;
		AccountAPI accountAPI = new AccountAPI(GlobalVar .sinaAccessToken);
		accountAPI.getUid(new myRequestListener(){

			@Override
			public void onComplete(String response) {
				int sIndex=response.indexOf("uid")+5;
				int eIndex=response.indexOf('}',sIndex);
				response=response.substring(sIndex,eIndex );
				sendMsg(handler,  Constants.MSG_GETONEWEIBO_SUCCESS, response);
				super.onComplete(response);
			}
			
		});
	}
	
	//获取单条微博信息
	public static void getWeiBo(final Handler handler,String weiboID)
	{
		if(!(GlobalVar.enWhich.equals("all")||GlobalVar.enWhich.equals("sina")))
			return;
		StatusesAPI statusesAPI =new StatusesAPI(GlobalVar.sinaAccessToken);
		statusesAPI.show(Long.parseLong(weiboID), new myRequestListener(){

			@Override
			public void onComplete(String response) {
				boolean isError =checkJsonError(handler, Constants.MSG_GETONEWEIBO_FAIL, response);
				if(!isError)
				{
					List<HashMap<String, String>> lArrData=SinaJsonAnalyzer.JsonToHasArr("{status:["+response+"]}", "status");
					 SinaJsonAnalyzer.getBigImgArr(lArrData);
					sendMsg(handler,  Constants.MSG_GETONEWEIBO_SUCCESS, lArrData);
				}
				super.onComplete(response);
			}

			@Override
			public void onError(WeiboException e) {
				checkJsonError(handler, Constants.MSG_GETONEWEIBO_FAIL, e.getMessage());
				super.onError(e);
			}
			
		});
		CommentsAPI commentsAPI =new CommentsAPI(GlobalVar.sinaAccessToken);
		commentsAPI.show(Long.parseLong(weiboID), 0, 0, 50, 1, AUTHOR_FILTER.ALL, new myRequestListener(){

			@Override
			public void onComplete(String response) {
				boolean isError =checkJsonError(handler, Constants.MSG_GETCOMMENTLIST_FAIL, response);
				if(!isError)
				{
					List<HashMap<String, String>> lArrData=SinaJsonAnalyzer.JsonToHasArr(response, "comments");
					for (HashMap<String, String> map : lArrData) {
						map.put("resource", "sina");
					}
					if(lArrData.size()==0) return;
					sendMsg(handler,  Constants.MSG_GETCOMMENTLIST_SUCCESS, lArrData);
				}
				super.onComplete(response);
			}

			@Override
			public void onError(WeiboException e) {
				checkJsonError(handler, Constants.MSG_GETCOMMENTLIST_FAIL, e.getMessage());
				super.onError(e);
			}
			
		});
		 statusesAPI.repostTimeline(Long.parseLong(weiboID), 0, 0, 50, 1, AUTHOR_FILTER.ALL,new myRequestListener(){

			@Override
			public void onComplete(String response) {
				boolean isError =checkJsonError(handler, Constants.MSG_GETREPOSTLIST_FAIL, response);
				if(!isError)
				{
					List<HashMap<String, String>> lArrData=SinaJsonAnalyzer.JsonToHasArr(response, "reposts");
					if(lArrData.size()==0) return;
					for (HashMap<String, String> hashMap : lArrData) {
						hashMap.put("resource", "sina");
					}
					sendMsg(handler,  Constants.MSG_GETREPOSTLIST_SUCCESS, lArrData);
				}
				super.onComplete(response);
			}

			@Override
			public void onError(WeiboException e) {
				checkJsonError(handler, Constants.MSG_GETREPOSTLIST_FAIL, e.getMessage());
				super.onError(e);
			}
			
		});
	}
	//获取我发出的评论
	public static void getCommentByMe(final Handler handler,String uid)
	{
		if(!(GlobalVar.enWhich.equals("all")||GlobalVar.enWhich.equals("sina")))
			return;
		CommentsAPI commentsAPI= new CommentsAPI(GlobalVar.sinaAccessToken);
		commentsAPI.byME(0, 0, 25, 1, SRC_FILTER.ALL, new myRequestListener(){

			@Override
			public void onComplete(String response) {
				List<HashMap<String, String>> lArrUserList=SinaJsonAnalyzer.JsonToHasArr(response, "comments");
				boolean isError = checkJsonError(handler, Constants.MSG_GETCOMMENT_FAIL, response);
			    if(!isError)
			    {
			    	sendMsg(handler, Constants.MSG_GETCOMMENT_SUCCESS, lArrUserList);
			    }
				super.onComplete(response);
			}

			@Override
			public void onError(WeiboException e) {
				checkJsonError(handler, Constants.MSG_GETCOMMENT_FAIL, e.getMessage());
				super.onError(e);
			}
			
		});
	}
	//获取我发出的评论
		public static void getCommentToMe(final Handler handler,String uid,String maxId,int count)
		{
			if(!(GlobalVar.enWhich.equals("all")||GlobalVar.enWhich.equals("sina")))
				return;
			CommentsAPI commentsAPI= new CommentsAPI(GlobalVar.sinaAccessToken);
			commentsAPI.toME(0, Long.parseLong(maxId), count, 1, AUTHOR_FILTER.ALL, SRC_FILTER.ALL,new myRequestListener(){

				@Override
				public void onComplete(String response) {
					List<HashMap<String, String>> lArrUserList=SinaJsonAnalyzer.JsonToHasArr(response, "comments");
					boolean isError = checkJsonError(handler, Constants.MSG_GETCOMMENT_FAIL, response);
				    if(!isError)
				    {
				    	sendMsg(handler, Constants.MSG_GETCOMMENT_SUCCESS, lArrUserList);
				    }
					super.onComplete(response);
				}

				@Override
				public void onError(WeiboException e) {
					checkJsonError(handler, Constants.MSG_GETCOMMENT_FAIL, e.getMessage());
					super.onError(e);
				}
				
			});
		}
    //删除评论
	public static void  deleteComment(final Handler handler,String uid)
	{
		if(!(GlobalVar.enWhich.equals("all")||GlobalVar.enWhich.equals("sina")))
			return;
		CommentsAPI commentsAPI = new CommentsAPI(GlobalVar.sinaAccessToken);
		commentsAPI.destroy(Long.parseLong(uid), new myRequestListener(){

			@Override
			public void onComplete(String response) {
				boolean isError = checkJsonError(handler, Constants.MSG_DELETECOMMENT_FAIL, response);                if(isError==false)
                {
                	sendMsg(handler, Constants.MSG_DELETECOMMENT_SUCCESS , null);
                }
				super.onComplete(response);
			}

			@Override
			public void onError(WeiboException e) {
				checkJsonError(handler,  Constants.MSG_DELETECOMMENT_FAIL, e.getMessage());
				super.onError(e);
			}
			
			
		});
	}
	//获取粉丝列表
	public static void getFollowersList(final Handler handler,String uid,int sIndex)
	{
		if(!(GlobalVar.enWhich.equals("all")||GlobalVar.enWhich.equals("sina")))
			return;
		FriendshipsAPI friendshipsAPI=new FriendshipsAPI(GlobalVar.sinaAccessToken);
		friendshipsAPI.followers(Long.parseLong(uid), 50, sIndex, true, new myRequestListener() {
			
			@Override
			public void onIOException(IOException e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onError(WeiboException e) {
				checkJsonError(handler, Constants.MSG_GETFOLLOWERS_FAIL, e.getMessage());
			}
			
			@Override
			public void onComplete4binary(ByteArrayOutputStream responseOS) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onComplete(String response) {
				super.onComplete(response);
				List<HashMap<String, String>> lArrUserList=SinaJsonAnalyzer.JsonToHasArr(response, "users");
				boolean isError = checkJsonError(handler, Constants.MSG_GETFOLLOWERS_FAIL, response);
			    if(!isError)
			    {
			    	if(lArrUserList!=null)
			    		for (HashMap<String, String> hashMap : lArrUserList) {
							hashMap.put("uid", hashMap.get("id"));
							hashMap.put("resource", "sina");
						}
			    	sendMsg(handler, Constants.MSG_GETFOLLOWERS_SUCCESS, lArrUserList);
			    }
				
			}
		});
	}
	//判断；判断两个A是否已关注B
	public static boolean Followed(String a_uid,String b_uid)
	{
		final boolean []rs=new boolean[1];
		FriendshipsAPI api=new FriendshipsAPI(GlobalVar.sinaAccessToken);
		api.show(Long.parseLong(a_uid), Long.parseLong(b_uid), new RequestListener() {
			
			@Override
			public void onIOException(IOException e) {
				// TODO Auto-generated method stub
				System.err.println("");
			}
			
			@Override
			public void onError(WeiboException e) {
				synchronized (rs) {
				  rs.notifyAll();	
				}
				
			}
			
			@Override
			public void onComplete4binary(ByteArrayOutputStream responseOS) {
				// TODO Auto-generated method stub
				System.err.println();
			}
			
			@Override
			public void onComplete(String response) {
				synchronized (rs) {
					try {
						String result = new JSONObject(response).getJSONObject("source").getString("following");
						if(result.equals("true"))
							rs[0]=true;
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					rs.notifyAll();
				}
				
				
			}
		});
		synchronized (rs) {
		try {
			rs.wait();
			return rs[0];
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}	
		}
		return rs[0];
	}
	//关注用户
	public static void follow(final Handler handler,String uid)
	{
		FriendshipsAPI api=new FriendshipsAPI(GlobalVar.sinaAccessToken);
		api.create(Long.parseLong(uid), null, new RequestListener() {
			
			@Override
			public void onIOException(IOException e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onError(WeiboException e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onComplete4binary(ByteArrayOutputStream responseOS) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onComplete(String response) {
				if(response.indexOf("screen_name")!=-1)
				{
					Message msg=new Message();
					msg.what=Constants.MSG_FOLLOW_SUCCESS;
					try {
						msg.obj=new JSONObject(response).get("id");
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					handler.sendMessage(msg);
				}
				
			}
		});
	}
	//获取关注列表
	public static void getFollowList(final Handler handler,String uid,int sIndex)
	{
		FriendshipsAPI friendshipsAPI=new FriendshipsAPI(GlobalVar.sinaAccessToken);
		friendshipsAPI.friends(Long.parseLong(uid), 50, sIndex, true, new RequestListener() {
			
			@Override
			public void onIOException(IOException e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onError(WeiboException e) {
				Message msg =new Message();
				msg.what=Constants.MSG_GETFOLLOWLIST_FAIL;
				handler.sendMessage(msg);
			}
			
			@Override
			public void onComplete4binary(ByteArrayOutputStream responseOS) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onComplete(String response) {
				Message msg =new Message();
				msg.what=Constants.MSG_GETFOLLOWLIST_SUCCESS;
				List<HashMap<String, String>> lArrUserList=SinaJsonAnalyzer.JsonToHasArr(response, "users");
				if(lArrUserList!=null)
				for (HashMap<String, String> hashMap : lArrUserList) {
					hashMap.put("uid", hashMap.get("id"));
					hashMap.put("resource", "sina");
				}
				msg.obj=lArrUserList;
 				handler.sendMessage(msg);
				
			}
		});
	}
	//获取朋友时间线
   public static void  getFriendline(Handler handler,String maxId)
   {
	   if(!(GlobalVar.enWhich.equals("all")||GlobalVar.enWhich.equals("sina")))
			return;
	   StatusesAPI statusesAPI=new StatusesAPI(GlobalVar.sinaAccessToken);
	   statusesAPI.friendsTimeline(0, Long.parseLong(maxId), 5, 1, false, FEATURE.ALL, false, new FriTimeLineListener(handler));
   }
	//获取朋友时间线
   public static void  getPubFriendline(Handler handler,String maxId,int count)
   {
	   if(!(GlobalVar.enWhich.equals("all")||GlobalVar.enWhich.equals("sina")))
			return;
	   StatusesAPI statusesAPI=new StatusesAPI(GlobalVar.sinaAccessToken);
	   statusesAPI.publicTimeline ( maxId,count, 1, false,new FriTimeLineListener(handler));
   }
 //获取@我的时间线
   public static void  getNoticeMeline(Handler handler,String maxId,int count)
   {
	   if(!(GlobalVar.enWhich.equals("all")||GlobalVar.enWhich.equals("sina")))
			return;
	   StatusesAPI statusesAPI=new StatusesAPI(GlobalVar.sinaAccessToken);
	   statusesAPI.mentions(0,Long.parseLong(maxId),count, 1, AUTHOR_FILTER.ALL, SRC_FILTER.ALL, TYPE_FILTER.ALL, false, new FriTimeLineListener(handler));
   }
 //取消关注
   public static void  cancelFollow(final Handler handler,String uid,String userName)
   {
	   if(!(GlobalVar.enWhich.equals("all")||GlobalVar.enWhich.equals("sina")))
			return;
	  FriendshipsAPI friendshipsAPI =new FriendshipsAPI(GlobalVar.sinaAccessToken);
	  friendshipsAPI.destroy( userName,new myRequestListener(){

		@Override
		public void onComplete(String response) {
			super.onComplete(response);
			boolean isError = checkJsonError(handler, Constants.MSG_CANCELFOLLOW_FAIL, response);
		    if(!isError)
		    {
		    	try {
					sendMsg(handler, Constants.MSG_CANCELFOLLOW_SUCCESS, new JSONObject(response).get("id"));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		    }
		}

		@Override
		public void onError(WeiboException e) {
			super.onError(e);
			checkJsonError(handler, Constants.MSG_CANCELFOLLOW_FAIL, e.getMessage());
		}
		  
	  });
   }
   
 //评论
   public static void  searchUser(final Handler handler,String q)
   {
	   if(!(GlobalVar.enWhich.equals("all")||GlobalVar.enWhich.equals("sina")))
			return;
	   SearchAPI searchAPI = new SearchAPI(GlobalVar.sinaAccessToken);
	   searchAPI.statuses(q, 100, new myRequestListener(){

			@Override
			public void onComplete(String response) {
				boolean isError =checkJsonError(handler, Constants.MSG_GETONEWEIBO_FAIL, response);
				if(!isError)
				{
					Log.v("search",response);
					response="{userarr:"+response+"}";
					List<HashMap<String, String>> hashLsData = SinaJsonAnalyzer.JsonToHasArr(response, "userarr");
				    for (HashMap<String, String> hashMap : hashLsData) {
				    	Log.v("search",hashMap.get("suggestion"));
					}
				}
				super.onComplete(response);
			}

			@Override
			public void onError(WeiboException e) {
				Log.v("search", e.getMessage());
				checkJsonError(handler, Constants.MSG_GETONEWEIBO_FAIL, e.getMessage());
				super.onError(e);
			}
			
		});
   }
   
 //获取朋友时间线
   public static void  getUserTimeline(Handler handler,String uid,String maxId,int count)
   {
	   if(!(GlobalVar.enWhich.equals("all")||GlobalVar.enWhich.equals("sina")))
			return;
	   StatusesAPI statusesAPI=new StatusesAPI(GlobalVar.sinaAccessToken);
	   statusesAPI.userTimeline(Long.parseLong(uid),0, Long.parseLong(maxId), count, 1, false, FEATURE.ALL, false, new FriTimeLineListener(handler));
   }
 //评论
   public static void  comment(final Handler handler,long id,String content)
   {
	   if(!(GlobalVar.enWhich.equals("all")||GlobalVar.enWhich.equals("sina")))
			return;
	   CommentsAPI commentsAPI=new CommentsAPI(GlobalVar.sinaAccessToken);
	   commentsAPI.create(content, id, false, new RequestListener() {
		
		@Override
		public void onIOException(IOException e) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onError(WeiboException e) {
			Message msg = new Message();
			   msg.what=Constants.MSG_COMMENT_FAIL;
			   msg.obj=e.getMessage();
			     handler.sendMessage(msg); // 向Handler发送消息,更新UI
		}
		
		@Override
		public void onComplete4binary(ByteArrayOutputStream responseOS) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onComplete(String response) {
			Message msg = new Message();
			   msg.what=Constants.MSG_COMMENT_SUCCESS;
			   try {
				msg.obj="sina"+new JSONObject(response).getString("id");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			     handler.sendMessage(msg); // 向Handler发送消息,更新UI
		}
	});
   }
   //转发
   public static void  repost(final Handler handler,long id,String content,boolean isComment)
   {
	   if(!(GlobalVar.enWhich.equals("all")||GlobalVar.enWhich.equals("sina")))
			return;
	   Log.v("log", id+"");
	   StatusesAPI statusesAPI=new StatusesAPI(GlobalVar.sinaAccessToken);
	   statusesAPI.repost(id, content,isComment==true?COMMENTS_TYPE.BOTH:COMMENTS_TYPE.NONE, new RequestListener() {
		
		@Override
		public void onIOException(IOException e) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onError(WeiboException e) {
			Message msg = new Message();
			   msg.what=Constants.MSG_REPOST_FAIL;
			   msg.obj=e.getMessage();
			     handler.sendMessage(msg); // 向Handler发送消息,更新UI
			
		}
		
		@Override
		public void onComplete4binary(ByteArrayOutputStream responseOS) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onComplete(String response) {
			Message msg = new Message();
			   msg.what=Constants.MSG_REPOST_SUCCESS;
			   try {
				msg.obj="sina"+new JSONObject(response).getString("id");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			     handler.sendMessage(msg); // 向Handler发送消息,更新UI
			
		}
	});
   }
   
   //发表一条微博
   public static void sendWeibo(String content)
   {
	   if(!(GlobalVar.enWhich.equals("all")||GlobalVar.enWhich.equals("sina")))
			return;
	   StatusesAPI api =new StatusesAPI(GlobalVar.sinaAccessToken);
	   api.update(content, null, null, null);
   }
 //获取用户信息
 	public static void getUserInfo(final Handler handler , String uid,String screen_name)
 	{
 		if(!(GlobalVar.enWhich.equals("all")||GlobalVar.enWhich.equals("sina")))
			return;
 		if(uid==null)
 			uid="0";
 		UsersAPI usersAPI=new UsersAPI(GlobalVar.sinaAccessToken);
 		usersAPI.show(Long.parseLong(uid),screen_name, new RequestListener() {
 			
 			@Override
 			public void onIOException(IOException e) {
 				// TODO Auto-generated method stub
 				
 			}
 			
 			@Override
 			public void onError(WeiboException e) {
 				// TODO Auto-generated method stub
 				
 			}
 			
 			@Override
 			public void onComplete4binary(ByteArrayOutputStream responseOS) {
 				// TODO Auto-generated method stub
 				
 			}
 			
 			@Override
 			public void onComplete(String response) {
 				Message msg = new Message();
 				   msg.what=Constants.MSG_GETUSERINFO_SUCCESS;
 				   List<HashMap<String, String>> lArrTimeline =SinaJsonAnalyzer.JsonToHasArr("{user:["+response+"]}","user");
 				   msg.obj=lArrTimeline;
 				     handler.sendMessage(msg); // 向Handler发送消息,更新UI
 				
 			}
 		});
 	}
     
 	
}

class FriTimeLineListener implements RequestListener
{

	Handler handler;
	public FriTimeLineListener(Handler handler)
	{
		this.handler=handler;
	}
	@Override
	public void onComplete(String response) {
		Message msg = new Message();
		   msg.what=Constants.MSG_GETTIMELINE_SUCCESS;
		   Log.v("content",response);
		   List<HashMap<String, String>> lArrTimeline =SinaJsonAnalyzer.JsonToHasArr(response,"statuses");
		   SinaJsonAnalyzer.getImgArr(lArrTimeline);
		  
		   msg.obj=lArrTimeline;
		     handler.sendMessage(msg); // 向Handler发送消息,更新UI
		
	}

	@Override
	public void onComplete4binary(ByteArrayOutputStream responseOS) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onIOException(IOException e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onError(WeiboException e) {
		Message msg = new Message();
		   msg.what=Constants.MSG_GETTIMELINE_FAIL;
		   msg.obj=e.getMessage();
		     handler.sendMessage(msg); // 向Handler发送消息,更新UI
		
	}
	

}

class myRequestListener implements RequestListener
{

	public boolean checkJsonError(Handler handler,int error_msg,String json)
 	{
		if(json.charAt(0)!='{') return false;
 		int error_code = SinaJsonAnalyzer.isErrorJson(json);
 		if(error_code==0)
 		{
 			return false;
 		}
 		else
 		{
 	      sendMsg(handler, error_msg, error_code);
 	      return true;
 		}
 	}
 	public void sendMsg(Handler handler,int msgType,Object obj)
 	{
 		    Message  msg =new Message();
			msg.what=msgType;
			msg.obj=obj;
			handler.sendMessage(msg);
 	}
	
	@Override
	public void onComplete(String response) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onComplete4binary(ByteArrayOutputStream responseOS) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onIOException(IOException e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onError(WeiboException e) {
		// TODO Auto-generated method stub
		
	}
	
}
